# -*- coding:utf-8 -*-

"""
    管理 device_id, sn_id, project_id 等
"""

import tornado.web
from service import base
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config



@route('/manage', 'manage')
class IndexPageHandler(base.BaseWebHandler):
    """ 设备管理 主页
    """

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        """ 获取设备列表
        """
        self.render('manage/list.html')


@route('/manage/get_all', 'manage.get_all')
class DeviceListHandler(base.BaseWebHandler):
    """ 获取所有数据
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        """ 获取设备列表
        """

        # 测试
        test_sn_ids_list = yield tornado.gen.Task(self.get_all_sn_ids, 'test')
        test_results = yield tornado.gen.Task(self.get_all_infos, test_sn_ids_list, 'test')

        # 正式
        online_sn_ids_list = yield tornado.gen.Task(self.get_all_sn_ids, 'online')
        online_results = yield tornado.gen.Task(self.get_all_infos, online_sn_ids_list, 'online')

        # 白名单
        from service import sn_id as global_test_sn_ids
        sn_ids = global_test_sn_ids.TOTAL_TEST_SN_IDS
        sn_ids = '; '.join(sn_ids)

        results = {
            'test_results':         test_results,
            'online_results':       online_results,
            'sn_ids':               sn_ids
        }
        logger.info('results:', results, caller=self)
        self.finish(results)

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self, *argl, **argd):
        self.get(*argl, **argd)

    @tornado.gen.engine
    def get_all_sn_ids(self, scope, callback):
        """ 获取所有sn_id
        """
        key = 'sn_ids_str'
        spec = {'scope': scope}
        sn_ids_list = yield tornado.gen.Task(mongo.distinct, self.db_name, self.collection_name, key, spec)
        logger.debug('sn_ids_list =', sn_ids_list, caller=self)
        callback(sn_ids_list)

    @tornado.gen.engine
    def get_all_infos(self, sn_ids_list, scope, callback):
        """ 获取所有设备所有项目的最新zip包数据
        """
        results = {}
        for sn_ids_str in sn_ids_list:
            spec = {'sn_ids_str': sn_ids_str, 'scope': scope}
            r = yield tornado.gen.Task(mongo.find_all, self.db_name, self.collection_name, spec)
            if not r:
                continue
            r.sort(key=lambda d: d['ver'])
            # results[sn_ids_str] = r[-1]
            results[sn_ids_str] = r
        logger.debug('results =', results, caller=self)
        callback(results)

